<?php
require_once __DIR__ . '/Table.php';
class Msg {
    protected static $tBody = 'msg_body';
    protected static $tClient = 'msg_client';
    protected static $tUid = 'msg_uid';


    /**
     * 新增消息
     * @param $client会话标识，$uid发布人，$detail消息内容
     */
    public static function setAdd($client, $uid, $detail)
    {
//        $cliDbs = DB::table($this->tClient)->where('del',0)
//            ->where('client',$client)->where('uid',$uid)->get();
//        $cliDbs =
        if (count($cliDbs)<2) {
            return array('code'=>'-2', 'msg'=>'会话成员空缺');
        }
        $cliDbs = $this->jsonToArr($cliDbs);
        //开启事务
        DB::beginTransaction();
        try {
            //看看消息本体
            $bodyId = DB::table($this->tBody)->insertGetId(['client' => $client,
                'own' => $uid, 'detail' => $detail, 'created_at' => time()]);
            //看看用户关联
            $uids = array();
            foreach ($cliDbs as $cliDb) {
                if ($cliDb['uid']!=$uid) {
                    DB::table($this->tUid)->insertGetId(['client' => $client,
                        'msgBody' => $bodyId, 'own' => $cliDb['uid'], 'uid' => $uid,
                        'created_at' => time()]);
                    $uids[] = $cliDb['uid'];
                }
            }
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$uids);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * JSON转化为数组
     */
    public static function jsonToArr($str) {
        if (is_string($str)) $str = json_decode($str);
        $arr = array();
        foreach($str as $k=>$v) {
            if(is_object($v) || is_array($v))
                $arr[$k] = self::jsonToArr($v);
            else
                $arr[$k] = $v;
        }
        return $arr;
    }
}